const app = getApp()
const db = wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    month:"",
    tasks: [], //当月的数据
    predict: 0, //当前用户本月的预计支出
    reality: 0, //当前用户本月实际支出
    commonSense: [], //文章列表
    newList:[] //
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let month = new Date().getMonth() + 1
    this.setData({
      month
    })
		wx.setNavigationBarTitle({
			title: this.data.month+'月预算',
		})
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTheMonthCount();
    this.getUserSet();
  },
  onClose(){
    this.setData({
      show:false
    })
  },
  showModel(){
    this.setData({
      show:true
    })
  },
  //获取用户的预计支出 
  getUserSet() {
    return new Promise(async(reslove, reject) => {
      db.collection("allAccount").where({
        _openid: app.globalData.openid,
      }).get().then(res => {
        try {
          this.setData({
            predict: res.data[0].monthPlan
          })
          reslove(res.data[0].monthPlan)
        } catch (error) {
          reslove()
        }
      })
    })
  },
  changEdit() {
    wx.showModal({
      title: '提示',
      content: '您是否确定更改本月预计支出',
      success: async(res) => {
        if (res.confirm) {
          await this.setUserPredict()
          this.setData({
            predict:this.data.predict,
            show:false
          })
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
        }
      }
    })
  },
  preDictChange(e) {
    this.data.predict = e.detail.value
  },
  //设置每月预计支出  
  setUserPredict() {
    return new Promise((reslove, reject) => {
      db.collection("allAccount").where({
        _openid: app.globalData.openid, //openid :根据用户的openid查询
      }).update({
        data: { monthPlan: Number(this.data.predict) }
      }).then((res) => {
        console.log(res)
        console.log('修改完成');
        reslove(res)
      })
    })
  },
  // 获取本月已经支出的金额总数
  getTheMonthCount() {
    return new Promise(async(reslove, reject) => {
      const MAX_LIMIT = 20
        // 先取出集合记录总数
      let countResult = await db.collection("otherRecord").where({
        _openid: app.globalData.openid, //openid :根据用户的openid查询
        recordMonth: this.data.month + '' //月份
      }).count()
      let total = countResult.total
        // 计算需分几次取
      let batchTimes = Math.ceil(total / 20)
      console.log("batchTimes", batchTimes)
      let tasks = []
      for (let i = 0; i < batchTimes; i++) {
        await db.collection("otherRecord").where({
            _openid: app.globalData.openid,
            recordMonth: this.data.month + ''
          }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
          .then(res => {
            tasks = tasks.concat(res.data)
            console.log('第', i, '次', res.data)
          })
      }
      
      this.tasks = tasks
      this.calcAmount(tasks)
      reslove(tasks)
    })
  },
  // 计算总金额
  calcAmount(list) {
    console.log(list,22222222)
    let count = 0
		let types =  ['食品', '交通', '购物', '寝室', '娱乐', '学习', '恋爱', '人情', '通讯', '数码', '网游', '医疗', '其他',]
    let newList = []
    
    // 根据types 生成一个页面渲染的数据数组 在这里生成是为了减少循环次数
    
    for (let i = 0; i < types.length; i++) {
      const element = types[i];
      let temp = {
        typeName:element,
        count:0, //
        counts:[] //拿来备用面得你说要做一个二级
      }
      newList.push(temp)
    }
    
      // 遍历数组 取出负增长的数据取绝对值 相加 得到本月实际支出
    list.forEach(element => {
      console.log(element)
      if (element.recordAmount.indexOf('-') > -1) {
        let _tempCount = Math.abs(element.recordAmount)
        let payType = element.payType
        let typeIndex = types.indexOf(payType)
        
        // 计算总的已用金额
        count += _tempCount
        
        // 计算分类的以用金额 这里如果没有类型的 就算做食品了 
        // 因为存的数据有问题
        if(typeIndex > -1){
          newList[typeIndex].count += _tempCount
        }else{
          newList[0].count += _tempCount
        }

      }
    });
    console.log(newList,444444)
    this.setData({
      reality: Number(count),
      newList
    })
  },
	getData:function(){
		wx.showLoading({
			title: '加载中',
		})
		db.collection("knowDetail")
		.get()
		.then(res => {
			this.setData({
				commonSense : res.data
			})
			wx.hideLoading()
		})
		.catch(err => {
			wx.showToast({
				title: '请重试',
			})
		})
	},
  toDetail: function(e) {
    let id = e.currentTarget.dataset.id
    let title = e.currentTarget.dataset.title
    wx.navigateTo({
      url: '/pages/me/knowledge/knowledge-detail/knowledge-detail?id=' + id + "&title=" + title,
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})